package com.hcf.admin.common.biz.user;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.hcf.admin.common.convention.exception.ClientException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.hcf.admin.common.convention.enums.UserErrorCodeEnum.USER_TOKEN_FAIL;

@Component
@RequiredArgsConstructor
public class UserContextInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        //排除注册路径
        if(method.equals("POST") && request.getRequestURI().equals("/api/shortlink/admin/v1/user")){
            return true;
        }

        String username = request.getHeader("username");
        String token = request.getHeader("token");
        if(StrUtil.isAllBlank(username, token)) {
            throw new ClientException(USER_TOKEN_FAIL);
        }
        Object user;
        try {
            user = stringRedisTemplate.opsForHash().get("login_" + username, token);
            if(user == null) throw new ClientException(USER_TOKEN_FAIL);
        }catch (Exception e){
            throw new ClientException(USER_TOKEN_FAIL);
        }
        UserInfo userInfo = JSON.parseObject(user.toString(), UserInfo.class);
        UserContext.set(userInfo);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();

    }
}
